package app.goods.info.services;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

import app.goods.info.constants.GlobalCache;
import app.goods.info.constants.UrlConstont;
import app.goods.info.services.domain.ShopGoodsInfo;
import app.goods.info.services.domain.ShopGoodsResponse;
import app.goods.info.utils.HttpClientUtils;
import app.goods.info.utils.UrlUtils;

public class ShopGoodsService {

	public List<ShopGoodsInfo> getAllShopGoods(String shopNo) {
		List<ShopGoodsInfo> result = new ArrayList<ShopGoodsInfo>();
		String queryUrl = UrlConstont.SHOP_GOODS_URL.replace("<shopNo>", shopNo);
		String responseBody = HttpClientUtils.get(UrlUtils.getRequestUrl(queryUrl), UrlUtils.builQueryParameters());
		if (StringUtils.isNotEmpty(responseBody)) {
			ShopGoodsResponse response = JSONObject.parseObject(responseBody, ShopGoodsResponse.class);
			if (response != null && response.getResult() != null) {
				result = response.getResult().getGoods();
			}
		}

		return result;
	}

	public List<ShopGoodsInfo> getFiltedShopGoods(List<ShopGoodsInfo> shopGoodsInfos) {
		return shopGoodsInfos.stream().filter(shopGoodsInfo -> isTargetCatalogue(shopGoodsInfo.getCatalogueNo()))
				.filter(shopGoodsInfo -> isTargetGoodsName(shopGoodsInfo.getGoodsName())).collect(Collectors.toList());
	}

	public List<ShopGoodsInfo> getFiltedShopGoods(String shopNo) {
		List<ShopGoodsInfo> result = getAllShopGoods(shopNo);
		return result.stream().filter(shopGoodsInfo -> isTargetCatalogue(shopGoodsInfo.getCatalogueNo()))
				.filter(shopGoodsInfo -> isTargetGoodsName(shopGoodsInfo.getGoodsName())).collect(Collectors.toList());
	}

	private boolean isTargetCatalogue(String catalogueNo) {
		return GlobalCache.getInstance().getTargetCataLogues().stream()
				.anyMatch(targetCata -> targetCata.getCatalogueNo().equals(catalogueNo)
						|| targetCata.getChildren().contains(catalogueNo));
	}

	private boolean isTargetGoodsName(String goodsName) {

		return GlobalCache.getInstance().getTargetGoodsNames().stream()
				.anyMatch(targetGoodsName -> targetGoodsName.equals(goodsName));
	}

}
